﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JGSY.Tasks
{
    public static class Task1
    {
        public static async Task Task001()
        {
            Console.WriteLine($"主线程ID: {Thread.CurrentThread.ManagedThreadId}");
            Console.WriteLine("开始演示Task的各种特性...\n");

            // 1. 创建并启动一个简单的Task (无返回值)
            Console.WriteLine("1. 创建并启动一个简单的Task (无返回值)");
            Task simpleTask = Task.Run(() => {
                Console.WriteLine($"简单任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1000);
                Console.WriteLine("简单任务完成");
            });
            await simpleTask;
            Console.WriteLine($"简单任务状态: {simpleTask.Status}\n");

            // 2. 创建并启动一个带返回值的Task
            Console.WriteLine("2. 创建并启动一个带返回值的Task");
            Task<int> taskWithResult = Task.Run(() => {
                Console.WriteLine($"计算任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1500);
                return 42;
            });
            int result = await taskWithResult;
            Console.WriteLine($"计算结果: {result}");
            Console.WriteLine($"计算任务状态: {taskWithResult.Status}\n");

            // 3. 演示Task的链式调用
            Console.WriteLine("3. 演示Task的链式调用");
            Task<string> chainedTask = Task.Run(() => {
                Console.WriteLine($"第一个任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1000);
                return "第一步完成";
            }).ContinueWith(previousTask => {
                Console.WriteLine($"第二个任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1000);
                return previousTask.Result + " -> 第二步完成";
            }).ContinueWith(previousTask => {
                Console.WriteLine($"第三个任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1000);
                return previousTask.Result + " -> 第三步完成";
            });
            string chainedResult = await chainedTask;
            Console.WriteLine($"链式调用结果: {chainedResult}\n");

            // 4. 演示Task的并行执行
            Console.WriteLine("4. 演示Task的并行执行");
            Task task1 = Task.Run(() => {
                Console.WriteLine($"任务1在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(2000);
                Console.WriteLine("任务1完成");
            });
            Task task2 = Task.Run(() => {
                Console.WriteLine($"任务2在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1500);
                Console.WriteLine("任务2完成");
            });
            Task task3 = Task.Run(() => {
                Console.WriteLine($"任务3在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(1000);
                Console.WriteLine("任务3完成");
            });
            await Task.WhenAll(task1, task2, task3);
            Console.WriteLine("所有并行任务完成\n");

            // 5. 演示Task的取消机制
            Console.WriteLine("5. 演示Task的取消机制");
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken token = cts.Token;

            Task cancelableTask = Task.Run(() => {
                Console.WriteLine($"可取消任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                for (int i = 0; i < 10; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        Console.WriteLine("检测到取消请求，任务将退出");
                        token.ThrowIfCancellationRequested();
                    }
                    Console.WriteLine($"可取消任务: {i}/10");
                    Thread.Sleep(500);
                }
                Console.WriteLine("可取消任务完成");
            }, token);

            // 3秒后取消任务
            await Task.Delay(3000);
            cts.Cancel();

            try
            {
                await cancelableTask;
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine($"任务状态: {cancelableTask.Status} ({cancelableTask.IsCanceled})\n");
            }

            // 6. 演示Task的异常处理
            Console.WriteLine("6. 演示Task的异常处理");
            Task faultedTask = Task.Run(() => {
                Console.WriteLine($"异常任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                throw new InvalidOperationException("模拟异常");
            });

            try
            {
                await faultedTask;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"捕获到异常: {ex.GetType().Name} - {ex.Message}");
                Console.WriteLine($"任务状态: {faultedTask.Status} ({faultedTask.IsFaulted})\n");
            }

            // 7. 演示Task的超时处理
            Console.WriteLine("7. 演示Task的超时处理");
            Task timeoutTask = Task.Run(() => {
                Console.WriteLine($"超时任务在线程 {Thread.CurrentThread.ManagedThreadId} 上执行");
                Thread.Sleep(3000);
                Console.WriteLine("超时任务完成（如果能执行到这一步）");
            });

            Task timeoutCheck = Task.Delay(1500);
            Task firstCompleted = await Task.WhenAny(timeoutTask, timeoutCheck);

            if (firstCompleted == timeoutCheck)
            {
                Console.WriteLine("任务执行超时！");
                Console.WriteLine($"超时任务状态: {timeoutTask.Status}\n");
            }
            else
            {
                Console.WriteLine("任务按时完成\n");
            }

            // 8. 演示ValueTask (C# 7.0+)
            Console.WriteLine("8. 演示ValueTask");
            ValueTask<int> valueTask = GetValueTaskAsync();
            int valueTaskResult = await valueTask;
            Console.WriteLine($"ValueTask结果: {valueTaskResult}\n");

            Console.WriteLine("所有Task演示完成");
        }

        static async ValueTask<int> GetValueTaskAsync()
        {
            await Task.Delay(500);
            return 100;
        }
    }
}
